import React, { useCallback, useEffect, useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { Text, View } from '@tarojs/components'
import { getPlatform, showToast } from '@UTILS/common'
import Images from '@ASSET/Images'
import Taro from '@tarojs/taro'
import { getWeRunData } from '@UTILS/wx'
import dataCenterActions from '@ACTIONS/dataCenter'
import { Analytic_Type } from '@CONSTANTS/analytic'
import ToDayDataHeader from '@COMPONENTS/DataCenter/ToDayDataHeader'
import { RootStateITF } from '@REDUXITF/index'
import { StepRecordITF } from '@INTERFACES/DataCenter'
import LoginVerifyBtn from '@COMPONENTS/Button/LoginVerifyBtn'
import style from './StepCard.module.scss'

const { isWX } = getPlatform()
interface Props {
  showLogin: () => void
}

const StepCard: React.FC<Props> = ({ showLogin }) => {
  const dispatch = useDispatch()
  const {
    dispatchSaveWeChatStepRecords, dispatchGetTodayStep
  } = dataCenterActions
  const saveWeChatStepRecords = useCallback(params => dispatch(dispatchSaveWeChatStepRecords(params)),
    [dispatch, dispatchSaveWeChatStepRecords])
  const getTodayStep = useCallback(() => dispatch(dispatchGetTodayStep()),
    [dispatch, dispatchGetTodayStep])
  const [isAuthorized, setIsAuthorized] = useState(false)
  const isVisitor = useSelector<RootStateITF, boolean>(state => state.profile.isVisitor)
  const todayStepRecord = useSelector<RootStateITF, StepRecordITF| null>(state => state.dataCenter.todayStepRecord)
  const getWxRunData = useCallback(async () => {
    let curIsAuthorized = false
    try {
      const runData = await getWeRunData()
      const hasData = runData?.length > 0
      curIsAuthorized = hasData
      hasData && saveWeChatStepRecords(runData)
    } catch (e) {
      curIsAuthorized = false
    }
    setIsAuthorized(curIsAuthorized)
  }, [saveWeChatStepRecords])
  const onClickAuth = useCallback(() => {
    Taro.tracker.trackEvent(Analytic_Type.num_click_step_auth.eventId)
    if (!isWX) {
      showToast('请打开微信小程序使用该功能')
      return
    }
    Taro.getSetting({
      success: res => {
        const runStatus = res.authSetting['scope.werun']
        if (runStatus || runStatus === undefined) {
          getWxRunData()
          return
        }
        Taro.openSetting({
          success: result => {
            if (result.authSetting['scope.werun']) getWxRunData()
          }
        })
      }
    })
  }, [getWxRunData])
  const initRunData = useCallback(() => {
    if (!isWX) return
    Taro.getSetting({
      success: res => {
        const runStatus = res.authSetting['scope.werun']
        !runStatus && setIsAuthorized(false)
        if (runStatus) {
          getWxRunData()
        }
      }
    })
  }, [getWxRunData])

  useEffect(() => {
    if (isVisitor) return
    getTodayStep()
    initRunData()
  }, [getTodayStep, initRunData, isVisitor])
  const { Calorie = 0, Distance = 0, Step = 0 } = todayStepRecord || {}
  const webHasData = todayStepRecord && !isWX
  const isShowData = isAuthorized && isWX || webHasData
  const distance = Step > 0 ? Math.max(0.1, Distance) : 0
  return (
    <View className={style.container}>
      <ToDayDataHeader src={Images.dataCenter.icon_today_step} title="步数" />
      <View className={style.stepContainer}>
        {isShowData ? (
          <>
            <Text className={style.todayStepText}>{Step}</Text>
            <Text className={style.flagText}>/5000 步</Text>
          </>
        ) : <Text className={style.noData}>暂无数据</Text>}
      </View>
      {isShowData ? (
        <Text className={style.distanceText}>
          {`${distance}千米  |  ${Calorie}卡路里`}
        </Text>
      ) : (
        <View className={style.content}>
          <LoginVerifyBtn onClick={onClickAuth} showLogin={showLogin}>
            <View className={style.btnContainer}>
              <Text className={style.btnText}>点击获得微信步数</Text>
            </View>
          </LoginVerifyBtn>
        </View>
      )}
    </View>
  )
}

export default StepCard
